package com.lzt.admin.common.security.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzt.admin.api.captcha.CaptchaAPI;
import com.lzt.admin.api.login.LoginConstantsAPI;
import com.lzt.admin.common.redis.config.RedisCore;
import com.lzt.admin.common.security.config.SecurityProperies;
import com.lzt.admin.common.security.core.SecurityVerify;
import com.lzt.admin.common.utils.SecurityVerifyUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

public class LoginFilter extends UsernamePasswordAuthenticationFilter implements CaptchaAPI, LoginConstantsAPI {
    @SneakyThrows
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equalsIgnoreCase("post")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        SecurityProperies securityProperties = (SecurityProperies) SpringUtil.getBean(SecurityProperies.class);
        if (request.getServletPath().equalsIgnoreCase(securityProperties.getProcessesUrl())) {
            verifyRetry(request,securityProperties);
            SecurityVerify securityVerify = (SecurityVerify) SpringUtil.getBean(SecurityVerify.class);
            if (ObjectUtil.isNotNull(securityVerify)) {
                securityVerify.verifyCode(request, securityProperties);
            }
            if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE) || request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE)) {
                try {
                    Map<String, String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
                    String username = map.get(securityProperties.getUsername());
                    String password = map.get(securityProperties.getPassword());
//                    String uuid = map.get(UUID);
                    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                    setDetails(request, authRequest);
                    return this.getAuthenticationManager().authenticate(authRequest);
                } catch (Exception ex) {
                    throw new BadCredentialsException(FAIL_CAPTCHA);
                }
            }
        }
        return super.attemptAuthentication(request, response);
    }
    private void verifyRetry(HttpServletRequest request, SecurityProperies securityProperties) throws IOException {
        RedisCore redisCache = (RedisCore) SpringUtil.getBean(RedisCore.class);
        String username = request.getParameter("username");
        String object = redisCache.getCacheObject(LOGIN_TOKEN_KEY + username);
        if(StrUtil.isNotBlank(object)){
            throw new BadCredentialsException("该帐户已经在其它电脑登录，请确认是否合法");
        }
        Collection<String> keys1 =  redisCache.keys(LOGIN_TOKEN_KEY + "*");
        if(keys1.size()>= securityProperties.getMaxNum()){
            throw new BadCredentialsException(USER_MAX_ERROR);
        }
        SecurityVerifyUtil securitUtil = (SecurityVerifyUtil) SpringUtil.getBean(SecurityVerifyUtil.class);
        String retryKey = securitUtil.getRetryKey(request);
        Integer retryCount = securitUtil.getRetryCount(retryKey);
        if(!securitUtil.isRetry(retryCount)){
            throw new BadCredentialsException(RETRY_ERROR_COUNT);
        }
    }
}
